<?php

namespace frontend\models;

use Yii;
use common\helpers\FileHelper;

class UserCharge extends \common\models\UserCharge
{
    public function rules()
    {
        return array_merge(parent::rules(), [
            // [['field1', 'field2'], 'required', 'message' => '{attribute} is required'],
        ]);
    }

    public function scenarios()
    {
        return array_merge(parent::scenarios(), [
            // 'scenario' => ['field1', 'field2'],
        ]);
    }

    public function attributeLabels()
    {
        return array_merge(parent::attributeLabels(), [
            // 'field1' => 'description1',
            // 'field2' => 'description2',
        ]);
    }



//海马第三方支付（公众号新版）
    public static function payHmApchange($amount, $code)
    {
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_type = self::CHARGE_TYPE_BANK;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        if (!$userCharge->save()) {
            return false;
        }
        require Yii::getAlias('@vendor/hm/HaimaPayment.php');
        require Yii::getAlias('@vendor/wx/WxTemplate.php');
        $haiMa = new \ApiClient();
        $haiMa->appId = HM_APPID;
        $haiMa->secret = HM_APPSECRET;
        $wx = new \WxTemplate();
        $tokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' .WX_APPID. '&secret=' .WX_APPSECRET. '&code=' . $code . '&grant_type=authorization_code';
        $info = $wx->getContents($tokenUrl);
        if(isset($info['errcode'])) {
            test('指令失效，请回交易页面重新发起');
        }
        $method = 'weixin.mppay';
        $content = [
            'merchant_no' => '20171103122605029858',
            'out_trade_no' => $userCharge->trade_no,
            'order_name' => '用户充值',
            'total_amount' => $userCharge->amount,
            'sub_appid' => WX_APPID,
            'sub_openid' => $info['openid'],
            'spbill_create_ip' => Yii::$app->request->userIP,
            'notify_url' => url(['site/hm-alipaynotify'], true),
        ];
        // 组装内容 并发送
        $result = $haiMa->call($method, $content);
        return $result;
    }

    //海马第三方支付 (新版)
    public static function payHmchange($amount, $tongdao = 'wechart')
    {
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_type = self::CHARGE_TYPE_ZFWECHART;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        $method = 'weixin.qr_code_pay';
        $content = [
            'sub_appid' => WX_APPID,
            'merchant_no' => '20171103122605029858',
            'out_trade_no' => $userCharge->trade_no,
            'order_name' => '用户充值',
            'total_amount' => $userCharge->amount,
            'spbill_create_ip' => Yii::$app->request->userIP,
            'notify_url' => url(['site/hm-alipaynotify'], true),
        ];
        if ($tongdao == 'alipay') {
            $userCharge->charge_type = self::CHARGE_TYPE_ALIPAY;
            $method = 'alipay.qr_code_pay';
            $content = [
                'merchant_no' => '20171103122605029858',
                'out_trade_no' => $userCharge->trade_no,
                'order_name' => '用户充值',
                'total_amount' => $userCharge->amount,
                'notify_url' => url(['site/hm-alipaynotify'], true),
            ];
        }
        if (!$userCharge->save()) {
            return false;
        }
        require Yii::getAlias('@vendor/hm/HaimaPayment.php');
        $haiMa = new \ApiClient();
        $haiMa->appId = HM_APPID;
        $haiMa->secret = HM_APPSECRET;
        // $sign = $haiMa->genSign($content);
        // 组装内容 并发送
        $result = $haiMa->call($method, $content);
        // test($result);
        if($result['error_code'] != '0') {
            return false;
        }
        //生成二维码
        require Yii::getAlias('@vendor/phpqrcode/phpqrcode.php');
        $value = $result['qr_code']; //二维码内容
        $errorCorrectionLevel = 'L';//容错级别   
        $matrixPointSize = 6;//生成图片大小   
        // $imgname =uniqid();
        $filePath = Yii::getAlias('@webroot/' . config('uploadPath') . '/hmchange/');
        FileHelper::mkdir($filePath);
        $src = $filePath . $tongdao . u()->id . '.png';
        //生成二维码图片   
        \QRcode::png($value, $src, $errorCorrectionLevel, $matrixPointSize, 2);
        return config('uploadPath') . '/hmchange/' . $tongdao . u()->id . '.png';
    }


//交易所第三方支付 98
    public static function quick($amount)
    {
        // $amount = 3;
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        $userCharge->charge_type = self::CHARGE_TYPE_BANK;
        if (!$userCharge->save()) {
            return false;
        }
        require Yii::getAlias('@vendor/hm/HaimaPayment.php');
        $haiMa = new \ApiClient();
        $haiMa->appId = HMWY_APPID;
        $haiMa->secret = HMWY_APPSECRET;
        $method = 'unionpay.fast';
        $content = [
            'out_trade_no' => $userCharge->trade_no,
            'total_amount' => $amount,
            'card_no' => post('card'),
            'total_amount' => $userCharge->amount,
            'notify_url' => url(['site/hmbank-alipaynotify'], true),
            'success_url' => url(['site/index'], true),
        ];
        // 组装内容 并发送
        $result = $haiMa->call($method, $content);
        // test($result);
        if($result['error_code'] == 0) {
            header("Location:" .$result['pay_url']. "");
            die;
        }
        
        return false;
    }

    //中安支付
    public static function payYifuPay($amount, $type)
    {
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        if($type == 1){
            //中安网银快捷
            $userCharge->charge_type = self::CHARGE_YIFU_NET;
            $service = YIFU_NET_NATIVE;
            $requestUrl = YIFU_NET_URL;
        }else{
            return false;
        }
        if (!$userCharge->save()) {
            return false;
        }
        $parameters = [];
        $parameters['service'] = $service;
        $parameters["charset"] = "UTF-8";
        $parameters["sign_type"] = "MD5";
        $parameters['custid'] = YIFU_CUST_ID;
        $parameters['out_trade_no'] = $userCharge->trade_no;
        $parameters['body'] = '用户余额充值';
        $parameters['attach'] = '用户余额充值';
        $parameters['total_fee'] = $amount * 100;
        $parameters['notify_url'] = url(['site/yifu-notify'], true);
        $parameters['return_url'] = url(['site/index'], true);
        require Yii::getAlias('@vendor/yifu/yifuPay.php');
        $yifuPay = new \yifuPay();
        if($type == 1){
            $parameters['type'] = "mobile";
        }
        $parameters['sign'] = $yifuPay->sign($parameters['out_trade_no']);
        $response = $yifuPay->request($requestUrl, $parameters);
        $response = json_decode($response, true);
        if(in_array($type, [2])){
            if($response['ret_code'] == 0 && $response['status'] == 1){
                return $response["code_img_url"];
            }else{
                file_put_contents("./pay_error.log", 'URL-----' . $requestUrl . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'REQUEST-----' . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'RESPONSE-----' . json_encode($response, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                return false;
            }
        }else{
            if($response['ret_code'] == 0 && $response['status'] == 1){
                return $response["url"];
            }else{
                file_put_contents("./pay_error.log", 'URL-----' . $requestUrl . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'REQUEST-----' . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'RESPONSE-----' . json_encode($response, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                return false;
            }
        }
    }

}
